// cloudfunctions/cancelCollection/index.js
const cloud = require('wx-server-sdk');
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
    try {
        const {
            collectionId,
            goodsId
        } = event;

        // 验证参数
        if (!collectionId || !goodsId) {
            return {
                success: false,
                message: '缺少必要参数'
            };
        }

        // 开始事务
        const transaction = await db.startTransaction();

        try {
            // 更新收藏状态
            await transaction.collection('user_collections').where({
                    _id: collectionId,
                    item_id: goodsId
                })
                .remove();

            // 更新商品收藏数
            await transaction.collection('blindbox_goods')
                .doc(goodsId)
                .update({
                    data: {
                        collectCount: _.inc(-1)
                    }
                });
            // 提交事务
            await transaction.commit();

            return {
                success: true,
                message: '取消收藏成功'
            };
        } catch (error) {
            // 回滚事务
            await transaction.rollback();
            throw error;
        }
    } catch (error) {
        console.error('取消收藏失败', error);
        return {
            success: false,
            message: error.message || '服务器错误',
            error: error.message
        };
    }
};